package com.lxmes.business.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.lxmes.base.domain.JcIteminfo;
import com.lxmes.base.domain.NcSupplier;
import com.lxmes.base.mapper.JcIteminfoMapper;
import com.lxmes.base.mapper.NcSupplierMapper;
import com.lxmes.business.domain.CcPurchaseInfoSp;
import com.lxmes.business.domain.ZcGeneralLedger;
import com.lxmes.business.mapper.CcPurchaseInfoSpMapper;
import com.lxmes.common.exception.ServiceException;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.NewNumber;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.sales.domain.NcContractExamine;
import com.lxmes.sales.mapper.NcContractExamineMapper;
import com.lxmes.system.service.ISysSpTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.business.mapper.CcPurchaseInfoMapper;
import com.lxmes.business.domain.CcPurchaseInfo;
import com.lxmes.business.service.ICcPurchaseInfoService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;

/**
 * 采购单Service业务层处理
 *
 * @author 张志煜
 * @date 2022-11-27
 */
@Service
public class CcPurchaseInfoServiceImpl implements ICcPurchaseInfoService
{
    @Autowired
    private CcPurchaseInfoMapper ccPurchaseInfoMapper;
    @Autowired
    private CcPurchaseInfoSpMapper purchaseInfoSpMapper;
    @Autowired
    private JcIteminfoMapper jcIteminfoMapper;
    @Autowired
    private NcSupplierMapper jcSupplierMapper;
    @Autowired
    private NcContractExamineMapper contractExamineMapper;
    @Autowired
    private ISysSpTaskService spTaskService;
    @Autowired
    protected Validator validator;
    /**
     * 查询采购单
     *
     * @param id 采购单主键
     * @return 采购单
     */
    @Override
    public CcPurchaseInfo selectCcPurchaseInfoById(Long id)
    {
        return ccPurchaseInfoMapper.selectCcPurchaseInfoById(id);
    }

    /**
     * 查询采购单列表
     *
     * @param ccPurchaseInfo 采购单
     * @return 采购单
     */
    @Override
    public List<CcPurchaseInfo> selectCcPurchaseInfoList(CcPurchaseInfo ccPurchaseInfo)
    {
        ccPurchaseInfo.setFactoryCode(SecurityUtils.getFactoryCode());
        return ccPurchaseInfoMapper.selectCcPurchaseInfoList(ccPurchaseInfo);
    }
    /*采购物料入库选择数据*/
    @Override
    public List<CcPurchaseInfo> selectCcPurchaseInfoSelectList(CcPurchaseInfo ccPurchaseInfo) {
        ccPurchaseInfo.setFactoryCode(SecurityUtils.getFactoryCode());
        return ccPurchaseInfoMapper.selectCcPurchaseInfoSelectList(ccPurchaseInfo);
    }

    @Override
    public List<CcPurchaseInfo> selectCcPurchaseInfoApplyList(CcPurchaseInfo ccPurchaseInfo) {
        ccPurchaseInfo.setFactoryCode(SecurityUtils.getFactoryCode());
        return ccPurchaseInfoMapper.selectCcPurchaseInfoApplyList(ccPurchaseInfo);
    }

    @Override
    @Transactional
    public List<CcPurchaseInfo> addCaigoItemInfo(Long[] ids) {
        List<CcPurchaseInfo> ccPurchaseInfoList = new ArrayList<>();
        List<JcIteminfo> jcIteminfoList = jcIteminfoMapper.selecIteminfoByIds(ids);
        if (jcIteminfoList.size() > 0) {
            for (JcIteminfo info : jcIteminfoList) {
                CcPurchaseInfo ccPurchaseInfo = new CcPurchaseInfo();
                ccPurchaseInfo.setItemCode(info.getItemCode());
                ccPurchaseInfo.setItemId(info.getItemCode());
                ccPurchaseInfo.setItemName(info.getItemName());
                ccPurchaseInfo.setClassId(info.getClassId());
                ccPurchaseInfo.setClassName(info.getClassName());
                ccPurchaseInfo.setSpec(info.getSpec());
                ccPurchaseInfo.setSupplyId(info.getSupplyId());
                ccPurchaseInfo.setSupplyName(info.getSupplyName());
                ccPurchaseInfo.setUnit(info.getUnit());
                ccPurchaseInfo.setUnitPrice(new BigDecimal("0.00"));
                ccPurchaseInfo.setTotalPrice(new BigDecimal("0.00"));
                ccPurchaseInfo.setJhUnitPrice(info.getJhPrice());
                ccPurchaseInfo.setYhNum(new BigDecimal("0"));
                ccPurchaseInfo.setShNum(new BigDecimal("0"));
                ccPurchaseInfo.setPackingNum(new BigDecimal("0"));
                ccPurchaseInfo.setYddNum(new BigDecimal("0"));
                ccPurchaseInfo.setTxm(info.getTmh());
                ccPurchaseInfo.setIsTuoguan(info.getIsTuoguan());
                ccPurchaseInfo.setCaizhi(info.getCaizhi());
                ccPurchaseInfo.setSize(info.getSize());
                ccPurchaseInfo.setSingleWeight(info.getSingleWeight());
                ccPurchaseInfo.setFigure(info.getFigure());
                ccPurchaseInfoList.add(ccPurchaseInfo);
            }
        }
        return  ccPurchaseInfoList;
    }
    /**
     * 新增采购单
     *
     * @param ccPurchaseInfo 采购单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCcPurchaseInfo(CcPurchaseInfo ccPurchaseInfo)
    {
        String number= NewNumber.createNewNumber(ccPurchaseInfoMapper.getNewCode(DateUtils.getDate()));
        List<CcPurchaseInfo> list = ccPurchaseInfo.getInfoList();
        if(list.size()>0){
            for ( CcPurchaseInfo info:list) {
                info.setFactoryCode(SecurityUtils.getFactoryCode());
                info.setFactoryName(SecurityUtils.getFactoryName());
                info.setDanhao("CGJH-"+number);
                info.setCreateTime(DateUtils.getNowDate());
                info.setCreateBy(SecurityUtils.getUsername());
                //JcIteminfo itemInfo = jcIteminfoMapper.selectJcIteminfoByItemCode(info.getItemCode());
                info.setYhTime(ccPurchaseInfo.getYhTime());
                info.setYhDanhao(info.getDanhao());
                info.setYhCompany(ccPurchaseInfo.getYhCompany());
                info.setYhType(ccPurchaseInfo.getYhType());
                info.setWlCompany(ccPurchaseInfo.getWlCompany());
                info.setCgName(ccPurchaseInfo.getCgName());
                info.setAsnDanhao(ccPurchaseInfo.getDanhao());
                info.setAsnDanhao(ccPurchaseInfo.getAsnDanhao());
                info.setDeptId(ccPurchaseInfo.getDeptId());
                //info.setHgNum(info.getYhNum());
                if(info.getJhUnitPrice().compareTo(new BigDecimal("0"))==-1){
                    info.setJhUnitPrice(new BigDecimal("0"));
                }
                NcSupplier supp = jcSupplierMapper.selectNcSupplierById(info.getSupplyId());
                if(supp!=null){
                    info.setSupplyName(supp.getSupplierName());
                }
                /*info.setRemark(ccPurchaseInfo.getRemark());*/
               /* if(info.getSupplyId()!=null){
                    //合同数量即采购数量
                info.setContractNum(info.getYhNum());
                    //查询是否是一个单号有相同供应商 如果有是一个合同号
                List<CcPurchaseInfo> supplyDanhaoList = ccPurchaseInfoMapper.selectCcPurchaseInfoListBydanhaoAndSupplyId(info);
                if(supplyDanhaoList.size()>0){
                    //查询是否是一个单号有相同供应商 如果有是一个合同号
                    info.setContractCode(supplyDanhaoList.get(0).getContractCode());
                }else {
                    //没有创建
                    String htNumber= NewNumber.createNewNumber(ccPurchaseInfoMapper.getHtNewCode(DateUtils.getDate()));
                    info.setContractCode("G"+htNumber);
                }
                }*/
                //info.setDeptId(SecurityUtils.getDeptId());
                ccPurchaseInfoMapper.insertCcPurchaseInfo(info);
            }
          /*  //发起审批
            spTaskService.addSpTask("SPCG001",number);*/
        }else {
            throw new ServiceException("物料不存在！");
        }
        return 1;

    }

    @Override
    @Transactional
    public int apply(CcPurchaseInfo ccPurchaseInfo) {
        List<CcPurchaseInfo> list = ccPurchaseInfo.getInfoList();
        String number= "CG_"+NewNumber.createNewNumber(purchaseInfoSpMapper.getNewCode(DateUtils.getDate()));
        if(list.size()>0){
            for ( CcPurchaseInfo info:list) {
                CcPurchaseInfo ccPurchaseInfo1 = ccPurchaseInfoMapper.selectCcPurchaseInfoById(info.getId());
//                if ("1".equals(ccPurchaseInfo1.getIsSp())) {
//                    throw new ServiceException(info.getItemCode()+"已经提交审批，不能重复提交！");
//                }

                if(StringUtils.isNull(info.getDeptId())){
                    throw new ServiceException("收货部门不能为空！！！");
                }
                CcPurchaseInfoSp sp=new CcPurchaseInfoSp();
                BeanUtils.copyProperties(info,sp);
                sp.setId(null);
                sp.setDanhao(number);
                sp.setYhDanhao(info.getDanhao());
                sp.setShenhFlag("0");
                sp.setShenhState("0");
                if(sp.getJhUnitPrice().compareTo(new BigDecimal("0"))==-1){
                    sp.setJhUnitPrice(new BigDecimal("0"));
                }
                //sp.setDeptId(SecurityUtils.getDeptId());
                purchaseInfoSpMapper.insertCcPurchaseInfoSp(sp);
                CcPurchaseInfo param = new CcPurchaseInfo();
                param.setId(info.getId());
                param.setIsSp("1");
                ccPurchaseInfoMapper.updateCcPurchaseInfo(param);
            }
            //发起审批
            spTaskService.addSpTask(ccPurchaseInfo.getSpCode(),number);
        }else {
            throw new ServiceException("物料不存在！");
        }
        return 1;
    }

    /**
     * 修改采购单
     *
     * @param ccPurchaseInfo 采购单
     * @return 结果
     */
    @Override
    public int updateCcPurchaseInfo(CcPurchaseInfo ccPurchaseInfo)
    {
        List<CcPurchaseInfo> list = ccPurchaseInfo.getInfoList();
        if(list.size()>0){
            for ( CcPurchaseInfo info:list) {
                info.setFactoryCode(SecurityUtils.getFactoryCode());
                info.setFactoryName(SecurityUtils.getFactoryName());
                info.setUpdateTime(DateUtils.getNowDate());
                info.setUpdateBy(SecurityUtils.getUsername());
                //JcIteminfo itemInfo = jcIteminfoMapper.selectJcIteminfoByItemCode(info.getItemCode());
                info.setYhTime(ccPurchaseInfo.getYhTime());
                info.setYhCompany(ccPurchaseInfo.getYhCompany());
                info.setYhType(ccPurchaseInfo.getYhType());
                info.setWlCompany(ccPurchaseInfo.getWlCompany());
                info.setCgName(ccPurchaseInfo.getCgName());
                info.setRemark(ccPurchaseInfo.getRemark());
                if(info.getJhUnitPrice().compareTo(new BigDecimal("0"))==-1){
                    info.setJhUnitPrice(new BigDecimal("0"));
                }
                NcSupplier supp = jcSupplierMapper.selectNcSupplierById(info.getSupplyId());
                if(supp!=null){
                    info.setSupplyName(supp.getSupplierName());
                }
                   /* if(info.getSupplyId()!=null){
                    //合同数量即采购数量
                    info.setContractNum(info.getYhNum());
                    //查询是否是一个单号有相同供应商 如果有是一个合同号
                    List<CcPurchaseInfo> supplyDanhaoList = ccPurchaseInfoMapper.selectCcPurchaseInfoListBydanhaoAndSupplyId(info);
                    if(supplyDanhaoList.size()>0){
                        //查询是否是一个单号有相同供应商 如果有是一个合同号
                        info.setContractCode(supplyDanhaoList.get(0).getContractCode());
                    }else {
                        //没有创建
                        String htNumber= NewNumber.createNewNumber(ccPurchaseInfoMapper.getHtNewCode(DateUtils.getDate()));
                        info.setContractCode("G"+htNumber);
                    }
                }*/
                ccPurchaseInfoMapper.updateCcPurchaseInfo(info);
            }
        }else {
            throw new ServiceException("物料不存在！");
        }
        return 1;
    }
    /*审批采购单*/
    @Override
    public int updateShenPi(CcPurchaseInfo ccPurchaseInfo) {
        ccPurchaseInfo.setShenhName(SecurityUtils.getUsername());
        //临时逻辑：审核后相当于合格 质检
        CcPurchaseInfo pur = ccPurchaseInfoMapper.selectCcPurchaseInfoById(ccPurchaseInfo.getId());
        ccPurchaseInfo.setHgNum(pur.getYhNum());
        return ccPurchaseInfoMapper.updateCcPurchaseInfo(ccPurchaseInfo);
    }

    @Override
    @Transactional
    public int updateShenHtSc(CcPurchaseInfo ccPurchaseInfo) {
        CcPurchaseInfo pur = ccPurchaseInfoMapper.selectCcPurchaseInfoById(ccPurchaseInfo.getId());
          if(pur.getSupplyId()!=null){
              //查询是否是一个单号有相同供应商 如果有是一个合同号
              CcPurchaseInfo ccpurInfo=new CcPurchaseInfo();
              ccpurInfo.setDanhao(pur.getDanhao());
              ccpurInfo.setSupplyId(pur.getSupplyId());
                List<CcPurchaseInfo> supplyDanhaoList = ccPurchaseInfoMapper.selectCcPurchaseInfoListBydanhaoAndSupplyId(ccpurInfo);
                if(supplyDanhaoList.size()>0){
                    //查询是否是一个单号有相同供应商 如果有是一个合同号
                    ccPurchaseInfo.setContractCode(supplyDanhaoList.get(0).getContractCode());
                }else {
                    //没有创建
                    String htNumber= NewNumber.createNewNumber(ccPurchaseInfoMapper.getHtNewCode(DateUtils.getDate()));
                    ccPurchaseInfo.setContractCode("G"+htNumber);
                }
              NcContractExamine con=new NcContractExamine();
              con.setConType("采购合同");
              con.setConCode(ccPurchaseInfo.getContractCode());
              con.setConName("采购-"+pur.getItemName());
              con.setSignName(pur.getSupplyName());
              con.setSignCode(pur.getSupplyId().toString());
              con.setProCode(pur.getItemId());
              con.setProName(pur.getItemName());
              con.setProNum(ccPurchaseInfo.getContractNum());
              con.setProMoney(ccPurchaseInfo.getContractNum().multiply(pur.getUnitPrice()));
              con.setAgent(SecurityUtils.getUsername());
              con.setConDate(new Date());
              contractExamineMapper.insertNcContractExamine(con);
              return ccPurchaseInfoMapper.updateCcPurchaseInfo(ccPurchaseInfo);
          }else {
              throw new ServiceException("采购单："+pur.getDanhao()+"未找到供应商！！！");
          }
    }

    /**
     * 批量删除采购单
     *
     * @param ids 需要删除的采购单主键
     * @return 结果
     */
    @Override
    public int deleteCcPurchaseInfoByIds(Long[] ids)
    {
        return ccPurchaseInfoMapper.deleteCcPurchaseInfoByIds(ids);
    }

    /**
     * 删除采购单信息
     *
     * @param id 采购单主键
     * @return 结果
     */
    @Override
    public int deleteCcPurchaseInfoById(Long id)
    {
        return ccPurchaseInfoMapper.deleteCcPurchaseInfoById(id);
    }

    @Override
    @Transactional
    public String imporIteminfo(List<JcIteminfo> infoList, boolean updateSupport, String operName,CcPurchaseInfo ccPurchaseInfo) {
        //导入物料信息表 无则插入有责不动
        if (StringUtils.isNull(infoList) || infoList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (JcIteminfo jcIteminfo : infoList)
        {
            try
            {
                BeanValidators.validateWithException(validator, jcIteminfo);
                jcIteminfo.setCreateBy(operName);
                jcIteminfo.setUpdateBy(operName);
                JcIteminfo jcIteminfo1 = jcIteminfoMapper.selectJcIteminfoByItemCode(jcIteminfo.getItemCode());
                if(StringUtils.isNull(jcIteminfo1)){
                    jcIteminfoMapper.insertJcIteminfo(jcIteminfo);
                }
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "<br/>恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        //新建采购计划
        String number= NewNumber.createNewNumber(ccPurchaseInfoMapper.getNewCode(DateUtils.getDate()));
        for (JcIteminfo iteminfo:infoList) {
            CcPurchaseInfo info = new CcPurchaseInfo();
            info.setFactoryCode(SecurityUtils.getFactoryCode());
            info.setFactoryName(SecurityUtils.getFactoryName());
            BeanUtils.copyProperties(iteminfo,info);
            info.setDanhao("CGJH-"+number);
            info.setCreateTime(DateUtils.getNowDate());
            info.setCreateBy(SecurityUtils.getUsername());
            info.setYhTime(ccPurchaseInfo.getYhTime());
            info.setYhDanhao(info.getDanhao());
            info.setYhCompany(ccPurchaseInfo.getYhCompany());
            info.setYhType(ccPurchaseInfo.getYhType());
            info.setWlCompany(ccPurchaseInfo.getWlCompany());
            info.setCgName(ccPurchaseInfo.getCgName());
            info.setAsnDanhao(ccPurchaseInfo.getDanhao()==null?"":ccPurchaseInfo.getDanhao());
            info.setDeptId(ccPurchaseInfo.getDeptId());
            info.setUnitPrice(iteminfo.getPrice());
            info.setTotalPrice(info.getUnitPrice().multiply(info.getYhNum()));
            info.setJhUnitPrice(new BigDecimal("0"));
            info.setYddNum(info.getYhNum());
            info.setSupplyName(ccPurchaseInfo.getSupplyName());
            info.setSupplyId(ccPurchaseInfo.getSupplyId());
            ccPurchaseInfoMapper.insertCcPurchaseInfo(info);
        }
        successMsg.insert(0, "生成采购单号为【"+"CGJH"+number+"】");
        return successMsg.toString();
    }
}
